package com.neuron.platform.tools;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class Influxdb4RTTools {
    private final String BUCKET = "application_realtime_db";
    private InfluxDBClient influxDBClient;

    public Influxdb4RTTools(String url, String token, String org) {
        this.influxDBClient = InfluxDBClientFactory.create(url, token.toCharArray(), org, BUCKET);
    }

    public Influxdb4RTTools() {
        String token = System.getenv("INFLUXDB_TOKEN");
        String org = System.getenv("INFLUXDB_ORG");
        String url = System.getenv("INFLUXDB_URL");
        if (!(StringUtils.isEmpty(token) && StringUtils.isEmpty(org) && StringUtils.isEmpty(url)))
            this.influxDBClient = InfluxDBClientFactory.create(url, token.toCharArray(), org, BUCKET);
    }

    @Tool(name = "run_Flux_to_query", description = "Run the Flux Ql statement to query")
    public String runFlux(String fluxQl) {
        return influxDBClient.getQueryApi().queryRaw(fluxQl);
    }

    @Tool(name = "query_equip_data", description = "The value of the device point is obtained according to the time interval  .")
    public String getEquipRealtimeData(@ToolParam String tenantCode,
                                       @ToolParam String equipmentName,
                                       @ToolParam(required = false) String functionType,
                                       @ToolParam String startTime,
                                       @ToolParam(required = false) String endTime) {
        String flux = "from(bucket: \"" + BUCKET + "\") " +
                "|> range(start: -" + startTime +
                (StringUtils.isEmpty(endTime) ? "" : ", stop: " + endTime) +
                ") " +
                "|> filter(fn: (r) => r[\"_measurement\"] == \"mp_raw_realtime_" + tenantCode + "\") " +
                "|> filter(fn: (r) => r[\"equipmentName\"] == \"" + equipmentName + "\") " +
                (StringUtils.isEmpty(functionType) ? "" : "|> filter(fn: (r) => r[\"functionType\"] == \"" + functionType + "\") ");
        String r = influxDBClient.getQueryApi().queryRaw(flux);

        return r;
    }
}
